<template>
  <el-row style="padding: 5px">
    <el-row>
      <el-card>
        <el-form :inline="true" :model="versionParams" class="" size="small">
          <el-form-item label="溯源产品">
            <el-select v-model="versionParams.sellproId" placeholder="请选择溯源产品">
              <el-option v-for="item in sellproOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本编号">
            <el-input v-model="versionParams.versionCode" placeholder="请输入版本编号"></el-input>
          </el-form-item>
          <el-form-item label="过期时间">
            <el-date-picker
              v-model="versionParams.expireDate"
              type="date"
              placeholder="选择过期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="selectVersionData">搜索</el-button>
            <el-button type="" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" plain icon="el-icon-plus" @click="addVersionData(1)" v-hasPermi="['agriculture:version:add']">新增</el-button>
            <button_disbable></button_disbable>
<!--            <el-button type="warning" plain icon="el-icon-download">导出</el-button>-->
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
    <el-row style="margin-top: 5px">
      <el-card>
        <el-table :data="tableData.slice((currentPage -1) *pageSize,currentPage*pageSize)" border style="width: 100%">
          <el-table-column align="center" prop="sellproName" label="溯源产品" width="150px"></el-table-column>
          <el-table-column align="center" prop="versionCode" label="版本编号"></el-table-column>
          <el-table-column align="center" prop="expireDate" label="过期时间" ></el-table-column>
          <el-table-column align="center" prop="remark" label="描述"></el-table-column>
          <el-table-column align="center" prop="" label="操作">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" class="mini_Button" @click="updateVersionData(scope.row,1)" v-hasPermi="['agriculture:version:edit']">修改</el-button>
              <el-button type="danger" icon="el-icon-delete" class="mini_Button" @click="deleteVersionData(scope.row.versionId)" v-hasPermi="['agriculture:version:remove']">删除</el-button>
              <el-button type="warning" icon="el-icon-setting" class="mini_Button" @click="goToCodePage">溯源码管理</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          style="margin: 20px 0; float: right"
          :current-page.sync="currentPage"
          background
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper,sizes"
          :total="this.tableData.length">
        </el-pagination>
      </el-card>
    </el-row>

    <el-dialog  :visible.sync="this.dialog" width="30%">
      <template v-slot:title>
        <div style="color: black;font-weight:1000; font-size: 20px;">{{dialogTitle}}</div>
      </template>
       <el-form :model="this.addVersion">
         <el-form-item  :label-width="300">
           <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>溯源产品</template>
           <el-select v-model="addVersion.sellproId" placeholder="请选择溯源产品" style="width:70%">
             <el-option v-for="item in sellproOptions"
             :key="item.value"
             :label="item.label"
             :value="item.value">
             </el-option>
           </el-select>
         </el-form-item>
         <el-form-item  :label-width="300">
           <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>版本编号</template>
           <el-input v-model="addVersion.versionCode" autocomplete="off" style="width:70%"></el-input>
         </el-form-item>
         <el-form-item :label-width="300">
           <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>过期时间</template>
           <el-date-picker
             v-model="addVersion.expireDate"
             type="date"
             placeholder="选择日期时间"
             style="width:70%">
           </el-date-picker>
         </el-form-item>
       </el-form>
       <div slot="footer" class="dialog-footer">
         <el-button @click="dialog=false">取 消</el-button>
         <el-button type="primary" @click="handleButtonClick">确 定</el-button>
       </div>
    </el-dialog>
  </el-row>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "@/views/iot/template/index.vue";
import {listVersion,addVersion,delVersion,updateVersion} from "@/api/agriculture/version";
import {listSellpro} from "@/api/agriculture/sellpro";
import Button_disbable from "@/views/agriculture/buttonDis/button_disbable.vue";
export default {
  components: {Button_disbable, Template},
  data() {
    const initialAddData={
      sellproId:'',
      versionCode:'',
      expireDate:'',
      remark:'',
      status:'',
      orderNum:'',
      delFlag:'',
    }
    return {
      currentPage:1,
      pageSize:10,
      dialogTitle:'',
      dialog:false,
      form:{
      },
      sellproOptions:'',
      addVersion:{ ...initialAddData },
      initialAddData,
      versionParams:{
        sellproId:'',
        versionCode:'',
        expireDate:'',
      },
      sellproParams:{
        sellproName:'',
        sellproArea:'',
        sellproWeight:'',
        sellproGuige:'',
        sellproImg:'',
        germplasmId:'',
        batchId:'',
        landId:'',
        deviceId:'',
        cameraId:'',
        staffId:'',
        shopId:'',
        h5Url:'',
        status:'',
        orderNum:'',
      },
      addOrUpdate:'',
      tableData: [],
      requiredFields :{ sellproId:'请选择溯源产品！', versionCode:'请填写溯源编号！', expireDate:'请选择过期日期！', }
    }
  },
  async mounted() {
    await this.getVersionList();
    },
  methods:{
    // 化时间日期
    changeTime(originalDateString){
      const originalDate = new Date(Date.parse(originalDateString));
      const year = originalDate.getFullYear();
      const month = String(originalDate.getMonth() + 1).padStart(2, '0');
      const day = String(originalDate.getDate()).padStart(2, '0');
      const hours = String(originalDate.getHours()).padStart(2, '0');
      const formattedDateString = `${year}-${month}-${day}`;
      return formattedDateString;
    },
    // 对话框确定按钮选择监听修改或新增
    handleButtonClick() {
      if (this.addOrUpdate === 1) {
        this.updateVersionData(this.addVersion, 2);
      } else {
        this.addVersionData(2);
      }
    },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
    // 查询溯源版本
    async selectVersionData()
    {
      this.versionParams.expireDate=this.changeTime(this.versionParams.expireDate)
      await this.getVersionList()
    },
    // 重置
    resetForm()
    {
      this.versionParams.versionCode='';
      this.versionParams.expireDate='';
      this.versionParams.sellproId='';
      this.getVersionList()
    },
    // 获取溯源版本列表
    async getVersionList()
    {
      const row1 = await listVersion(this.versionParams)
      const row2 = await listSellpro(this.sellproParams)
      this.sellproOptions = row2.rows.map(item => ({
        value: item.sellproId,
        label: item.sellproName
      }));
      this.tableData =row1.rows.map(item1=>{
      const findData =row2.rows.find(item2 => item1.sellproId === item2.sellproId)
       return {
         ...item1,
         sellproName:findData.sellproName
       }
     })
    },
    // 添加溯源版本
    async addVersionData(buttonId)
    {
      if(buttonId == 1) {this.addVersion = { ...this.initialAddData };this.dialogTitle ='添加溯源版本';this.dialog= true; this.addOrUpdate = 0}
      else if(buttonId == 2) {
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addVersion[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await addVersion(this.addVersion)
          this.openMessage('success', '添加成功！');
          await this.getVersionList()
          this.dialog = false
        } catch (error) {
          console.error('添加溯源版本错误:', error);
          this.openMessage('error', '添加失败！');
        }
      }
    },
    // 修改溯源版本
    async updateVersionData(row,buttonId)
    {
      if(buttonId == 1) {this.addVersion= {...row} ;this.dialogTitle ='修改溯源版本';this.dialog=true;this.addOrUpdate = 1 }
      else if(buttonId == 2){
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addVersion[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await updateVersion(this.addVersion)
          this.openMessage('success', '修改成功！');
          await this.getVersionList()
          this.dialog = false
        }catch (error){
          console.error('Error occurred while update sellpro:', error);
          this.openMessage('error', '修改失败！');
        }
      }
    },
    // 删除溯源版本
    async deleteVersionData(id)
    {
      this.$confirm('确认删除？')
        .then(async _ => {
          try {
            delVersion(id)
            this.openMessage('success', '删除成功！');
            await this.getVersionList()
          } catch (error) {
            console.log("溯源版本删除错误:", error)
            this.openMessage('error', '删除失败！');
          }
        }).catch(_ => {
        return
      });
    },
    // 跳转页面
    goToCodePage()
    {
      this.$router.push('/trace/code');
    },
  }
}
</script>
<style scoped>
.mini_Button{
  font-size:11px;
  padding: 4px 9px
}
</style>
